import React, { useContext, useEffect, useMemo, useRef, useState } from 'react'
import classNames from 'classnames';
import moment from 'moment';
import { Spin, Form, DatePicker /* , Tooltip */, Select, message } from 'antd';
import { useMount } from 'react-use';

import { isSuccess } from '@/utils/request';
import OrganizationSelect from '@/components/OrganizationSelect';
import { fetchOrganizationListAndDefault } from '@/pages/SalaryManage/utils';

import Search from '@/pages/SalaryManage/components/SuperSearch';
import TwoColHead from '@/pages/SalaryManage/components/TwoColHead';
import {
    feedbackReceiveEnum,
    feedbackHandleEnum,
    feedbackProblemTypeEnum,
    feedbackAssignTypeEnum
} from '@/pages/SalaryManage/enum';
import AutoDivider from '@/pages/SalaryManage/components/AutoDivider';
import { queryHandled, queryDateRange } from '@/services/salaryManage/salaryConfirm';
import { commonColumn, dateColumn, datetimeColumn } from '@/pages/SalaryManage/utils/TableUtil';
import EmptyPlaceHolder from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import EmployeeNameWrapper from '@/pages/SalaryManage/components/EmployeeNameWrapper';
import { TabStoreContext } from '@/pages/SalaryManage/constant/TabStoreContext';
import salaryStyle from '@/pages/SalaryManage/salaryManage.less';

import useFetchCountInfo from './hooks/useFetchCountInfo';
import useTableWrapper from './hooks/useTableWrapper';

const { MonthPicker, RangePicker } = DatePicker;
const { Option } = Select;

const problemTypeList = feedbackProblemTypeEnum.list();

const SearchWrapper = React.forwardRef(
    ({ form, onSearch, monthRange, model, organizationList }, ref) => {
        const { store: { organizationCode }, mergeTabStore } = useContext(TabStoreContext);
        const { getFieldDecorator } = form;
        ref(form);

        const disabledDate = current => {
            if (current && monthRange?.length) {
                return monthRange.indexOf(current.startOf('month').format('YYYY-MM-DD')) === -1;
            }
            if (!monthRange?.length) {
                return true;
            }
            return !monthRange;
        };

        const onChangeMonth = (date, dateString) => {
            mergeTabStore({
                period: dateString
            });
        };

        const handleOrganizationChange = value => {
            form.setFieldsValue({
                period: undefined,
                employeeCode: undefined,
                receiver: undefined,
                v_salaryDate: undefined
            });
            mergeTabStore({
                period: undefined,
                organizationCode: value
            });
        };

        return (
            <div>
                <Search.Wrapper onSearch={onSearch}>
                    <TwoColHead
                        left={
                            <Search.Commonly>
                                <Search.Item label="行政机构">
                                    {getFieldDecorator('organizationCode', {
                                        initialValue: organizationCode
                                    })(
                                        <OrganizationSelect
                                            isStrictly
                                            isNeedPermission
                                            style={{ width: 220 }}
                                            treeDataFromProp
                                            treeDataList={organizationList}
                                            onChange={handleOrganizationChange}
                                            allowClear={false}
                                        />
                                    )}
                                </Search.Item>
                                <Search.Item label="月份">
                                    {getFieldDecorator('v_salaryDate', { initialValue: model?.v_salaryDate })(
                                        <MonthPicker disabledDate={disabledDate} onChange={onChangeMonth} />
                                    )}
                                </Search.Item>
                            </Search.Commonly>
                        }
                        right={
                            <TwoColHead
                                right={
                                    <AutoDivider>
                                        {/* <Tooltip title="自定义表头">
                                        <BizIcon
                                            type="searchbar_modifyheader_icon_default"
                                            className={salaryStyle.iconfont22}
                                        />
                                    </Tooltip> */}
                                    </AutoDivider>
                                }
                                addMarginAtOuter={false}
                                addMarginInRightChild={false}
                                style={{ flex: 1 }}
                            />
                        }
                        addMarginInRightChild={false}
                    />

                    <Search.More>
                        <Search.Item label="提交时间">
                            {getFieldDecorator('v_submitTime')(<RangePicker style={{ width: '220px' }} />)}
                        </Search.Item>
                        <Search.Item label="问题类型">
                            {getFieldDecorator('problemType', {
                                initialValue: null
                            })(
                                <Select placeholder="请选择">
                                    <Option value={null}>全部</Option>
                                    {problemTypeList.map(type => (
                                        <Option key={type.value} value={type.value}>
                                            {feedbackProblemTypeEnum.getShowName(type.value)}
                                        </Option>
                                    ))}
                                </Select>
                            )}
                        </Search.Item>
                    </Search.More>
                </Search.Wrapper>
            </div>
        );
    }
);

const tableColumns = (/* {  operateConfig = {} } */) => [
    {
        title: (
            <EmployeeNameWrapper
                left={
                    <span
                        className={classNames(salaryStyle.circle)}
                        style={{ visibility: 'hidden' }}
                    />
                }
                name="姓名"
            />
        ),
        dataIndex: 'employeeName',
        fixed: 'left',
        width: 146,
        render(text, record) {
            return (
                <EmployeeNameWrapper
                    left={
                        <span
                            className={classNames(salaryStyle.circle)}
                            style={{ visibility: record.receiver ? 'hidden' : 'visible' }}
                        />
                    }
                    name={<span title={text}><EmptyPlaceHolder value={text} /></span>}
                />
            );
        }
    },
    commonColumn({
        title: '工号',
        dataIndex: 'employeeNo',
        fixed: 'left',
        width: 120
    }),
    commonColumn({
        title: '组织机构',
        dataIndex: 'departmentName',
        width: 220
    }),
    dateColumn(
        {
            title: '薪资月份',
            dataIndex: 'salaryDate',
            width: 95
        },
        { pattern: 'YYYY-MM' }
    ),
    datetimeColumn({
        title: '提交时间',
        dataIndex: 'submitTime',
        width: 180
    }),
    commonColumn({
        title: '反馈编号',
        dataIndex: 'feedbackNo',
        width: 120
    }),
    {
        title: '反馈内容',
        dataIndex: 'feedback',
        width: 250,
        render(text) {
            return (
                <pre
                    style={{
                        marginBottom: 0,
                        display: 'inline-block',
                        whiteSpace: 'break-spaces',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </pre>
            );
        }
    },
    commonColumn({
        title: '接收人',
        dataIndex: 'receiver',
        width: 132
    }),
    {
        title: '接收状态',
        dataIndex: 'receiveStatus',
        width: 80,
        render(text) {
            return <EmptyPlaceHolder value={feedbackReceiveEnum.getShowName(text)} />;
        }
    },
    {
        title: '处理状态',
        dataIndex: 'status',
        width: 80,
        render(text) {
            return <EmptyPlaceHolder value={feedbackHandleEnum.getShowName(text)} />;
        }
    },
    {
        title: '问题类型',
        dataIndex: 'problemType',
        width: 100,
        render(text) {
            return <EmptyPlaceHolder value={feedbackProblemTypeEnum.getShowName(text)} />;
        }
    },
    commonColumn({
        title: '解决时间',
        dataIndex: 'resolveTime',
        width: 180
    }),
    commonColumn({
        title: '耗时',
        dataIndex: 'timeConsuming',
        width: 100
    }),
    commonColumn({
        title: '处理结果',
        dataIndex: 'respondContent',
        width: 200,
        render(text) {
            return (
                <pre
                    style={{
                        marginBottom: 0,
                        display: 'inline-block',
                        whiteSpace: 'break-spaces',
                        wordBreak: 'break-all'
                    }}
                >
                    <EmptyPlaceHolder value={text} />
                </pre>
            );
        }
    }),
    {
        title: '分配方式',
        dataIndex: 'assignType',
        width: 100,
        render(text) {
            return <EmptyPlaceHolder value={feedbackAssignTypeEnum.getShowName(text)} />;
        }
    }
];

const Handled = () => {
    const { store: { organizationCode, period }, mergeTabStore } = useContext(TabStoreContext);

    const [pageLoading, setPageLoading] = useState(false);
    const { pagination, setDataSource, setPagination, render: TableWrapper } = useTableWrapper();
    const [monthRange, setMonthRange] = useState([]);
    const [organizationTreeData, setOrganizationTreeData] = useState({});
    const [selectOrganizationCode, setSelectOrganizationCode] = useState(null);
// 获取页签统计个数
    const fetchCountInfo = useFetchCountInfo();
    const searchForm = useRef();

    const getSearchCondition = () => searchForm.current?.getFieldsValue();
    // 获取查询条件
    const getPostData = searchCondition => {
        const { v_salaryDate, v_submitTime, ...postData } = searchCondition;

        if (v_salaryDate) {
            postData.salaryDate = v_salaryDate?.startOf('month')?.format('YYYY-MM-DD');
        }

        if (v_submitTime && v_submitTime.length > 0) {
            postData.submitStartTime = v_submitTime[0].startOf('day').format('YYYY-MM-DD HH:mm:ss');
            postData.submitEndTime = v_submitTime[1].endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }

        return {
            ...postData,
            pageNo: postData?.current || pagination.current || 1,
            pageSize: postData?.pageSize || pagination.pageSize || 10
        };
    };

    const search = searchCondition => {
        const preCondition = (!searchCondition || (searchCondition?.current || searchCondition?.pageSize))
            ? { organizationCode: selectOrganizationCode, ...getSearchCondition(), ...searchCondition || {} }
            : searchCondition;
        const postData = getPostData(preCondition);

        if (!organizationCode && postData.organizationCode) {
            mergeTabStore({
                organizationCode: postData.organizationCode
            });
        }
        setPageLoading(true);
        queryHandled(postData)
            .then(searchResponse => {
                if (isSuccess(searchResponse)) {
                    const { pageSize, total, pageNo: current, rows } = searchResponse.data;
                    setDataSource(rows);
                    setPagination({
                        ...pagination,
                        pageSize: pageSize || 10,
                        current: current || 1,
                        total
                    });
                    fetchCountInfo({ organizationCode: postData.organizationCode });
                } else {
                    message.error(searchResponse.msg);
                }
            })
            .finally(() => setPageLoading(false));
    };

    const EnhancedSearchWrapper = useMemo(
        () =>
            Form.create({
                /* 不立即搜索
            onValuesChange: (props, changedValues, allValues) => {
                search(allValues);
            }
            */
            })(SearchWrapper),
        []
    );

    useEffect(() => {
        const requestOrganizationCode = selectOrganizationCode;

        if (requestOrganizationCode) {
            queryDateRange({ organizationCode: requestOrganizationCode }).then(response => {
                if (isSuccess(response)) {
                    const range = response.data;
                    setMonthRange(range && range.length > 0 ? range : []);
                } else {
                    message.error(response.msg);
                }
            });
        }
    }, [selectOrganizationCode]);

    useEffect(() => {
        setSelectOrganizationCode(organizationCode);
    }, [organizationCode]);

    useMount(() => {
        fetchOrganizationListAndDefault(organizationCode)
            .then(({ organizationResponse, defaultOrganizationCode: defaultSelectCode }) => {
                setOrganizationTreeData(organizationResponse);
                setSelectOrganizationCode(defaultSelectCode);

                const condition = getPostData({
                    ...getSearchCondition(),
                    organizationCode: defaultSelectCode,
                    v_salaryDate: period ? moment(period, 'YYYY-MM-DD') : null
                });
                if (defaultSelectCode) {
                    search(condition);
                }
            });
    });

    const salaryDate = period ? moment(period, 'YYYY-MM-DD') : null;

    return (
        <Spin spinning={pageLoading}>
            <EnhancedSearchWrapper
                monthRange={monthRange}
                onSearch={search}
                wrappedComponentRef={form => {
                    searchForm.current = form;
                }}
                model={{
                    v_salaryDate: salaryDate
                }}
                organizationCode={selectOrganizationCode}
                organizationList={organizationTreeData}
            />
            <TableWrapper columns={tableColumns({})} search={search} />
        </Spin>
    );
};

export default React.memo(Handled);
